import {getAccessToken} from "@/utils/token";
import {message} from "antd";
import api from "@/utils/api";
import stringUtil from "@/utils/stringUtil";

/**
 * 获取上传URL
 */
export const getUploadFileUrl = () => {
  const {NODE_ENV} = process.env;
  if (NODE_ENV === 'development') {
    return api.dev + api.uploadFile;
  }
  return api.pro + api.uploadFile;
};

/**
 * 上传文件
 *
 * @param type
 * @param fileTag
 * @param actionRef
 */
export const uploadFile = (type: string, fileTag: string, actionRef: any) => {
  return {
    name: 'file',
    action: getUploadFileUrl(),
    data: {
      'type': type,
      'fileTag': fileTag
    },
    headers: {
      Authorization: getAccessToken(),
    },
    showUploadList: false, // 不展示上传列表
    // 变化
    onChange(info: any) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功!`);
        actionRef.current?.reloadAndRest?.();
      } else if (info.file.status === 'error') {
        const data = info.file.response;
        const msg = (data.data === null || stringUtil.isEmpty(data?.data?.exceptionMsg)) ? data.msg : data.data.exceptionMsg;
        message.error(`${info.file.name} 文件上传失败!,失败原因:${msg}`);
      }
    }
  }
};
